package com.codingfuture.glaciercollect.listener;

import com.alibaba.fastjson.JSON;
import com.codingfuture.glaciercollect.dto.ReceptionDTO;
import com.codingfuture.glaciercollect.dto.THDateDTO;
import com.codingfuture.glaciercollect.service.MeterRecordService;
import com.codingfuture.glaciercommon.util.System;
import net.dreamlu.iot.mqtt.spring.client.MqttClientTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.loadbalancer.config.LoadBalancerCacheAutoConfiguration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @Author: Sun
 * @DateTime: 2025/4/15 17:50
 * @Description:
 **/
@Component
public class MqttListen {
    @Autowired
    private MqttClientTemplate client;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MeterRecordService meterRecordService;

    /**
     * 订阅
     *
     * @return
     */
    public boolean sub() {
        client.subQos0("/topic/subscribe_temperature", (context, topic, message, payload) -> {

            String s = new String(payload, StandardCharsets.UTF_8);
            System.blue.println(s);
            //把监听到消息转换成dto
            ReceptionDTO receptionDTO = JSON.parseObject(s, ReceptionDTO.class);

            THDateDTO thDateDTO = new THDateDTO();
            thDateDTO.setSn(receptionDTO.getType());
            thDateDTO.setTem(receptionDTO.getData().getTemp());
            thDateDTO.setHum(receptionDTO.getData().getHumidity());

            //发布消息
            String jsonResult = JSON.toJSONString(thDateDTO);//把结果类转化为JSON发布出去
            redisTemplate.convertAndSend(thDateDTO.getSn(), jsonResult);
            System.yellow.println(thDateDTO);

            //插入详细数据
            meterRecordService.addInfor(thDateDTO);
        });
        return true;
    }
}
